package cheme.ProcessModel.Interpreter;

import java.util.StringTokenizer;

import cheme.ProcessModel.IModelElement;
import cheme.ProcessModel.ModelEnv;
import cheme.ProcessModel.ProcessUnits.Streams.Tags.AbstractTagComponent;
import cheme.ProcessModel.ProcessUnits.Streams.Tags.QuantityField;

/*
 * This parses an expression in the quantity field of a tag component and 
 * applies some tokenCheck function to each. 
 */
public abstract class TagComponentQuantityIteratingRule implements IRule
{
	protected Interpreter interpreter = null;
	QuantityField quantity = null;
	private AbstractTagComponent component = null;
	
	protected abstract RuleResult tokenCheck(String quantityToken);
	
	public RuleResult applyTo(IModelElement object)
	{
		setComponent((AbstractTagComponent)object);
		RuleResult result = new IRule.Success(getComponent());
		
		/*
		 * If one of these conditions are true, no need to test.
		 */
		boolean bIsInitial = getComponent().isInitial();
		boolean bHasUnknownValue = getComponent().hasUnknownValue();
		//if(!getComponent().isInitial() && !getComponent().hasUnknownValue())
		if(!bIsInitial && bHasUnknownValue)
		{
			interpreter = ModelEnv.getInstanceFor(getComponent()).getInterpreter();
			String quantity = getComponent().getQuantity();
			String token = "";

			StringTokenizer tokenizer = new StringTokenizer(quantity, " \t+-()*^/\\", true); //true entails delimters are returned as tokens

			while(tokenizer.hasMoreTokens() && (result instanceof IRule.Success))
			{
				token = tokenizer.nextToken().trim();
				result = tokenCheck(token);
			}
		}
		
		return result;
	}

	/**
	 * @param component the component to set
	 */
	public void setComponent(AbstractTagComponent component)
	{
		this.component = component;
	}

	/**
	 * @return the component
	 */
	public AbstractTagComponent getComponent()
	{
		return component;
	}
}
